<template>
  <div class="center-container">
    <h1>查询余额</h1>
    <div class="button-group">
      <van-button
        square
        style="background: #51915d; color: white; border-radius: 8px;"
        @click="getAccountInfo"
        :loading="isLoading"
        class="btn-primary"
        title="点击获取账户信息"
      >
        {{ isLoading ? "获取账户信息中..." : "💰获取账户信息" }}
      </van-button>
    </div>
    <div class="account-info">
      <p class="info">
        当前账户地址: <span>{{ shortenedAccountAddress }}</span>
      </p>
      <p class="info">当前余额: <span>{{ balance }}</span> ETH</p>
    </div>
  </div>
</template>

<script>
import { web3 } from '../util';

export default {
  data() {
    return {
      accountAddress: '',
      balance: 0,
      isLoading: false, // 用于控制加载状态
    };
  },
  computed: {
    // 计算属性，用于格式化账户地址
    shortenedAccountAddress() {
      if (!this.accountAddress) return 'N/A';
      const start = this.accountAddress.slice(0, 6); // 前6位
      const end = this.accountAddress.slice(-4); // 后4位
      return `${start}...${end}`; // 格式化后的地址
    },
  },
  methods: {
    async getAccountInfo() {
      this.isLoading = true; // 开始加载
      try {
        const accounts = await window.ethereum.request({
          method: 'eth_requestAccounts',
        });

        this.accountAddress = accounts[0];

        const balanceInWei = await web3.eth.getBalance(this.accountAddress);
        this.balance = web3.utils.fromWei(balanceInWei, 'ether');
      } catch (error) {
        console.error('Error fetching account info:', error);
      } finally {
        this.isLoading = false; // 加载完成
      }
    },
  },
};
</script>

<style>
@import url('../../styles/global.css');

.center-container {
  margin: 20px;
  padding: 20px;
  border: 1px solid #cccccc6c;
  border-radius: 5px;
  background-color: #f9f9f940;
  font-family: 'Arial', sans-serif; /* 设置默认字体 */
}

h1 {
  color: #51915d;
  margin-bottom: 20px;
  font-family: 'Arial', sans-serif; /* 设置默认字体 */
}

.button-group {
  margin-bottom: 20px;
}

.info {
  margin: 10px 0;
  color: #555;
  font-size: 16px;
  font-family: 'Arial', sans-serif; /* 设置默认字体 */
}

.info span {
  font-weight: bold;
  color: #333;
}
</style>
